package com.zsk.shop.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zsk.shop.common.base.NoMsgException;
import com.zsk.shop.common.constant.Constant;
import com.zsk.shop.common.constant.StaticConfigUtil;
import com.zsk.shop.common.enums.SmsEnum;
import com.zsk.shop.config.aop.ParamLogger;
import com.zsk.shop.common.base.model.sms.SmsModel;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author lv
 * @date 2019/4/11 13:55
 */
@Component
public class DingTalkRootUtil {

    //java内部开发
    public static final String groupA = "";
    //项目团队消息通知群
    public static final String groupB = "https://oapi.dingtalk.com/robot/send?access_token=9562da93ab0d6f7c74ea591c144eb4020cd29469fa445ee602a63e3ef39e15a1";

    //正式环境异常提醒通知群
    public static final String groupC = "https://oapi.dingtalk.com/robot/send?access_token=4ac51e4c0c7dc684a80530f27a80d4b882baeeda9c7a5ca32d4a739d211b9e0d";

    //其他通知群
    public static final String group = "";

    private static final Logger logger = LoggerFactory.getLogger(DingTalkRootUtil.class);

    /**
     * 钉钉机器人发送消息通用
     *
     * @param content   发送内容
     * @param atMobiles 提示手机号 中间用，分割
     * @param noticeAll 是否@提示
     */
    public Boolean send(String content, String atMobiles, Boolean noticeAll) {
        String uri = "";
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request != null) {
            uri = request.getRequestURI();
        }
        String WEBHOOK_TOKEN;
        if (StaticConfigUtil.getEnv().equals("local")) {
//            WEBHOOK_TOKEN = groupA;
//            本地不提示报错到钉钉
            return true;
        } else if (Constant.isProd()) {
            WEBHOOK_TOKEN = groupC;
        } else {
            WEBHOOK_TOKEN = groupB;
        }
        String param = ParamLogger.requestJsonParam(request);
        if (ToolUtil.isEmpty(param)) {
            param = JSONObject.toJSONString(request.getParameterMap());
        }
        content = "环境:" + StaticConfigUtil.getEnv() + "\n" +
                "请求token:" + HttpContext.getToken() + "\n" +
                "请求user:" + HttpContext.getSafeUserNo() + "\n" +
                "请求IP:" + HttpUtil.getIpAddress(request) + "\n" +
                "请求地址:" + uri + "\n" +
                "请求参数:" + param.replaceAll("\"", "\'") + "\n" +
                content;
        content = "监控报警:" + content;
        //处理发送前的"号问题，所有都替换成’
        content = content.replaceAll("\"", "'");
        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(WEBHOOK_TOKEN);
        httppost.addHeader("Content-Type", "application/json; charset=utf-8");
        content = StringUtils.abbreviate(content, 1300);
        String textMsg = "{" +
                "     \"msgtype\": \"text\"," +
                "     \"text\": {" +
                "         \"content\": \"" + content + "\"" +
                "     }," +
                "     \"at\": {" +
                "         \"atMobiles\": [" + atMobiles + "], " +
                "         \"isAtAll\": " + noticeAll + "" +
                "     }" +
                " }";
        StringEntity se = new StringEntity(textMsg, "utf-8");
        httppost.setEntity(se);
        try {
            httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 钉钉机器人发送验证码内容
     *
     * @param content   发送内容
     * @param atMobiles 提示手机号 中间用，分割
     * @param noticeAll 是否@提示
     * @param needSend  是否正常发送
     */
    public Boolean sendOtherInfo(String content, String atMobiles, Boolean noticeAll, Boolean needSend) {
        if (!needSend) {
            return true;
        }
        //判断发送区域
        String WEBHOOK_TOKEN;
        if (StaticConfigUtil.getEnv().equals("local")) {
//            本地不提示报错到钉钉
            return true;
        } else {
            WEBHOOK_TOKEN = groupB;
        }
        content = "环境:" + StaticConfigUtil.getEnv() + "\n" +
                content;
        content = "监控报警:" + content;
        //处理发送前的"号问题，所有都替换成’
        content = content.replaceAll("\"", "'");
        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(WEBHOOK_TOKEN);
        httppost.addHeader("Content-Type", "application/json; charset=utf-8");
        content = StringUtils.abbreviate(content, 1300);
        String textMsg = "{" +
                "     \"msgtype\": \"text\"," +
                "     \"text\": {" +
                "         \"content\": \"" + content + "\"" +
                "     }," +
                "     \"at\": {" +
                "         \"atMobiles\": [" + atMobiles + "], " +
                "         \"isAtAll\": " + noticeAll + "" +
                "     }" +
                " }";
        StringEntity se = new StringEntity(textMsg, "utf-8");
        httppost.setEntity(se);
        try {
            httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 发送验证消息至钉钉群
     *
     * @param phone        接受手机号
     * @param templateCode 阿里云短信模板编号
     * @param code         验证码
     * @param result       运营商是否发送成功
     */
    public void sendSmsInfo(String phone, String templateCode, String code, Boolean result, JSONObject object) throws NoMsgException {
        if (Constant.isProd()) {
            this.sendOtherInfo("", "", false, false);
            return;
        }
        String content = SmsEnum.getContentByCode(templateCode);
        String errorMsg = "";
        if (!result) {
            SmsModel smsModel = JSON.parseObject(object.toJSONString(), SmsModel.class);
            errorMsg = "当前运营商发送短信内容失败：" + smsModel.getMessage();
            throw new NoMsgException(errorMsg);
        }
        content = String.format(content, code);
        String msg = "\n" + errorMsg + "\n\n开始发送短信：接受手机号码为：【" + phone + "】\n发送内容为:【" + content + "】";
        this.sendOtherInfo(msg, "", false, true);
    }

}
